package com.xiaokui.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.xiaokui.common.exception.base.BaseException;
import com.xiaokui.common.utils.DateUtils;
import com.xiaokui.nursing.domain.*;
import com.xiaokui.nursing.dto.CheckInApplyDto;
import com.xiaokui.nursing.dto.CheckInConfigDto;
import com.xiaokui.nursing.dto.CheckInContractDto;
import com.xiaokui.nursing.dto.CheckInElderDto;
import com.xiaokui.nursing.mapper.*;
import com.xiaokui.nursing.utils.CodeGenerator;
import com.xiaokui.nursing.vo.CheckInConfigVo;
import com.xiaokui.nursing.vo.CheckInDetailVo;
import com.xiaokui.nursing.vo.CheckInElderVo;
import com.xiaokui.nursing.vo.ElderFamilyVo;
import lombok.AllArgsConstructor;
import net.sf.jsqlparser.util.validation.metadata.DatabaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xiaokui.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author xiaokui
 * @date 2025-06-10
 */
@Service
@AllArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{

    private CheckInMapper checkInMapper;
    private CheckInConfigMapper checkInConfigMapper;
    private ElderMapper elderMapper;
    private ContractMapper contractMapper;
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper=new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo()).eq(Elder::getStatus,1);
        Elder elder=elderMapper.selectOne(elderLambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elder)){
            throw new BaseException("老人已入住");
        }
        //更新床位状态为已入住
        Bed bed=bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //更新或保存老人基本信息
        Elder elderIn=saveOrUpdate(dto.getCheckInElderDto(),bed);
        //保存入住信息
        CheckIn checkIn=saveCheckIn(dto,elderIn);
        //保存入住配置信息
        saveCheckInConfig(dto.getCheckInConfigDto(),checkIn);
        //保存合同信息
        String contractCode="HT"+ CodeGenerator.generateContractNumber();
        saveContract(dto,contractCode,elderIn);
    }



    /**
     * 保存或更改老人信息
     * @param dto
     * @param bed
     */
    private Elder saveOrUpdate(CheckInElderDto dto,Bed bed){
        Elder elder=new Elder();
        //拷贝属性
        BeanUtils.copyProperties(dto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //判断老人信息是否已存在
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper=new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,dto.getIdCardNo()).ne(Elder::getStatus,1);
        Elder elder1=elderMapper.selectOne(elderLambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elder1)){
            elderMapper.updateById(elder);
        }
        else{
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     *保存入住信息
     * @param dto
     * @param elder
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto,Elder elder){
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 保存入住配置信息
     * @param dto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInConfigDto dto,CheckIn checkIn){
        CheckInConfig checkInConfig=new CheckInConfig();
        BeanUtils.copyProperties(dto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     *
     * @param dto
     * @param contractCode
     */
    private void saveContract(CheckInApplyDto dto,String contractCode,Elder elder){
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractCode);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isAfter(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }


    /**
     * 查看入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo=new CheckInDetailVo();
        CheckIn checkIn=checkInMapper.selectById(id);
        //查询老人基本信息
        Elder elder=elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询亲属信息
        List<ElderFamilyVo> list= (List<ElderFamilyVo>) JSON.parse(checkIn.getRemark());
        checkInDetailVo.setElderFamilyVoList(list);
        //查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig=checkInConfigMapper.selectOne(lambdaQueryWrapper);
        CheckInConfigVo checkInConfigVo=new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查询合同信息
        LambdaQueryWrapper<Contract> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Contract::getElderId,elder.getId());
        Contract contract=contractMapper.selectOne(lambdaQueryWrapper1);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}
